package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.AliOSSUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author wuJiaWei
 * @version 1.0
 */
@RestController
@Slf4j
public class UploadController {
    @Autowired
    private AliOSSUtils aliOSSUtils;
    @PostMapping("/upload")
    public Result upload(String username, Integer age, @RequestParam("image") MultipartFile file) throws IOException {
        log.info("文件上传:{},{},{}",username,age,file);
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //构建新的文件名
        String extname = null;//文件扩展名
        if (originalFilename != null) {
            extname = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String newFileName = UUID.randomUUID().toString()+extname;//随机名+文件扩展名
        //将文件存储在服务器的磁盘目录
        file.transferTo(new File("F:/images/"+newFileName));
        return Result.success();
    }
    @SneakyThrows
    @PostMapping("/upload2")
    public Result upload2(MultipartFile image) {
        log.info("文件上传名称:{}",image.getOriginalFilename());
        String url = aliOSSUtils.upload(image);
        log.info("文件上传完成，文件访问的url:{}",url);
        return Result.success(url);
    }
}
